package com.bupt.ilink.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OssClient {
    private static final Logger log = LoggerFactory.getLogger(OssClient.class);

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.access-key-id}")
    private String accessKeyId;

    @Value("${oss.access-key-secret}")
    private String accessKeySecret;

    @Getter
    @Value("${oss.bucket-name}")
    private String bucketName;

    private OSS ossClient;
    private boolean isShutdown = false;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    public OSS getClient() {
        return ossClient;
    }

    @PreDestroy
    public void shutdown() {
        if (ossClient != null && !isShutdown) {
            ossClient.shutdown();
            isShutdown = true;
            log.info("OSS client has been shut down.");
        }
    }

}
